package com.lgc.leetcode.easy.longestCommonPrefix;

/**
 * 求最大公共前缀
 */
public class Program {
    public static void main(String[] args) {
        Program program = new Program();

        String[] strs = new String[]{"flower", "flow", "flight"};
        System.out.println(program.longestCommonPrefix(strs));

        String[] strs2 = new String[]{"aa","a"};
        System.out.println(program.longestCommonPrefix(strs2));

        int a = 0;
    }

    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0){
            return "";
        }

        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            int len = result.length() < strs[i].length() ? result.length() : strs[i].length();
            result = result.substring(0,len);
            for (int j = 0; j < len; j++) {
                if (result.charAt(j) != strs[i].charAt(j)) {
                    result = result.substring(0, j);
                    break;
                }
            }

            if (result.length() == 0) {
                break;
            }
        }

        return result;
    }
}
